/**
 * 系统信息
 * 包含config文件中的配置信息
 */

import {defineStore} from 'pinia'
// import {wxLogin, getAreaTree, getemployeecode} from '@/api/app'
// import {logout, AppLogin, userTransferLinkageMember} from '@/api/user'
import miniApp from '@/util/platform/miniApp/index'
// import {defaultUserInfo} from './user'
import uniApi from '@/util/uniApi'
// import user from './user'
// import cart from './cart'
import {clone} from 'lodash'
// import government from './government'
import _platform from '@/util/platform/index'
import dayjs from "dayjs";
import {Encrypt,AESDecrypt} from '../util/lib/crypto'

const app = defineStore({
	id: 'app', state: () => ({
		token: '', searchSource: 0, // 全局变量，请求来源，0-平台 1-门店 2-商城
		addressData: [], // 省市区地址数据缓存
		payParams: {}, // 查询订单支付参数
		relaunchUrl: '', // 跳转到登录页前的页面地址及参数信息
		sk: '', // sk
		inviteCode: '', // 邀请码
		MySK: '', // 我的sk
		invitationCode: '', // 我的邀请码
		invitationQrCode: '', // 我的邀请码 二维码
		drawDown: {
			memberDrawDown: false,
			memberDrawDownImg: ''
		},
		nowDays: 0,
		netWorkType: '', // 当前网络类型
		privacyPolicy: false, // 隐私政策弹窗是否同意
		privacyModal: {
			show: false,
			resolvePrivacyAuthorization: () => {
			}
		} // 小程序隐私政策弹窗
	}), actions: {
		// 参数sk
		setSK(sk) {
			this.sk = sk
		},
		// 参数 邀请码
		setInviteCode(invitationCode) {
			this.inviteCode = invitationCode
		},
		// 我的sk
		getMySK() {
			getemployeecode().then(({data}) => {
				this.MySK = data.mySk
				this.invitationCode = data.invitationCode
				this.invitationQrCode = data.qrCode
			})
		},
		// 忽略版本号
		setIgnoreVersion(version) {
			this.ignoreVersion = version
		},
		// 应用登录
		async init(options) {
			const {storeId = '', showLoading = true, token = false, reLogin = false} = options || {}
			try {

				this.closeRegister(2)
				// 小程序端登录
				// 登录即可获取用户全部信息
				// #ifdef MP-WEIXIN

				const code = await miniApp.getWxCode() || ''
				let {data = {}} = await wxLogin({
					code, storeId, token: token ? this.token : null, sk: this.sk || '',
					deviceInfo: _platform.device
				}, showLoading)
				if (data.whetherHintTransfer) {
					await this.modal(data)
				}

				if (data.memberRegisterImg && this.nowDays !== dayjs().format('YYYY-MM-DD')) {
					this.openRegister(2, data.memberRegisterImg,data.memberRegisterUrl)
					this.nowDay()
				}
				await this.UserInfoInit(data)
				// #endif

				// App端登录
				// #ifdef APP-PLUS
				// 已经登录过的用户，不再静默登录
				if (!user().userInfo?.mobile || reLogin) {
					let {data: result = {}} = await AppLogin({})
					console.log('静默登录原始信息:', result)
					if (result.memberRegisterImg && this.nowDays !== dayjs().format('YYYY-MM-DD')) {
						this.openRegister(2, result.memberRegisterImg,result.memberRegisterUrl)
						this.nowDay()
					}
					await this.UserInfoInit(result)
				}
				// #endif
				return Promise.resolve(true)
			} catch (error) {
				console.log('登录异常：：', error)
				console.log('登录异常：：', wx.getLaunchOptionsSync().scene)
				if (wx.getLaunchOptionsSync().scene !== 1154) return
				let {data = {}} = await wxLogin({
					code: '', storeId, token: token ? this.token : null, sk: this.sk || '',
					deviceInfo: _platform.device
				}, showLoading)
				await this.UserInfoInit(data)
			}
		},
		nowDay(){
			this.nowDays = dayjs().format('YYYY-MM-DD')
		},
		// 弹窗
		openRegister(type, img, url) {
			switch (type) {
			case 2:
				this.drawDown = {
					memberDrawDown: true,
					memberDrawDownImg: img,
					memberRegisterUrl: url
				}
				break
			}
		},
		// 关闭 弹窗
		closeRegister(type) {
			switch (type) {
			case 2:
				this.drawDown = {
					memberDrawDown: false,
					memberDrawDownImg: '',
					memberRegisterUrl: '',
				}
				break
			}
		},
		// 用户信息初始化
		async UserInfoInit(data = {}) {
			// token初始化
			this.token = data.token || ''
			// 用户信息初始化
			let userInfo = {}
			for (const key in defaultUserInfo) {
				userInfo[key] = data[key]
			}
			if (userInfo.mobile) {
				userInfo.mobile = AESDecrypt(userInfo.mobile)
			}
			user().$patch({
				userInfo
			})
			// 初始化时获取用户购物车数据
			if (userInfo.mobile) {
				await cart().getBookCartNumber()
			}
			// 政企账号信息初始化
			government().setGovernmentInfo({id: ''})
			// 获取我的sk
			getemployeecode().then(({data}) => {
				console.log('我的邀请码++++++++',data)
				this.MySK = data.mySk
				this.invitationCode = data.invitationCode
				this.invitationQrCode = data.qrCode
			})

			this.checkConnectWifi({openId: data.wxOpenid, phone: data.mobile})
		}, // 小程序退出登录
		async logOut() {
			logout().then(() => {
				this.payParams = {}
				user().$patch({
					userInfo: clone(defaultUserInfo)
				})
				uni.clearStorage()
				uniApi.loading()
				setTimeout(async () => {
					await this.init()
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}, 800)
			})
		}, // 设置登录前的页面地址及参数信息
		setRelaunchUrl(url) {
			url = url ? encodeURIComponent(url) : ''
			this.relaunchUrl = url
		}, // 修改请求来源
		setSearchSource(value) {
			this.searchSource = value
		}, // 省市区地址数据缓存
		async getAddressData() {
			if (this.addressData.length) {
				return this.addressData
			}
			const {data} = await getAreaTree()
			// 递归处理数据字段名称
			const recurrence = (list) => {
				list.forEach(item => {
					item.value = item.code
					item.text = item.name
					item.children = item.childRegion
					delete item.code
					delete item.name
					delete item.childRegion
					if (item.children && item.children.length) {
						recurrence(item.children)
					}
				})
			}
			recurrence(data)
			this.addressData = data
			return data
		}, // 提交订单跳转支付页
		usePayCashier(options) {
			/**
			 * @type {string} payCode				- * 支付单号
			 * @type {string} orderParams 	-   查询订单参数, 可多个参数用&拼接
			 * @type {number} backUrlKey		- * 跳转类型为0时必填支付成功后的回调地址
			 * @type {number} jumpType			-   跳转至支付页方式 默认0 [0: 关闭当前页重定向(如提交订单页), 1: 普通跳转可返回原页面(订单详情)]
			 */
			const {orderParams, payCode, backUrlKey, jumpType = 0, payAmount} = options
			// 必要参数校验
			if (!payCode) {  
				return uniApi.toast({title: '支付单号不能为空', icon: 'none'})
			} 
			if (jumpType === 0 && !backUrlKey) {
				return uniApi.toast({title: '回调地址不能为空', icon: 'none'})
			}
			// orderParams 字段类型校验
			if (orderParams && typeof orderParams !== 'string') {
				return uniApi.toast({title: '请序列化订单参数, 带&符号', icon: 'none'})
			}
			// 调整页面传参为全局自定义N个参数方法
			this.payParams = {
				orderParams, payCode, backUrlKey,  jumpType, payAmount
			}
			switch (jumpType) {
			case 0:
				uniApi.redirect('/pages/pay/pay')
				break
			case 1:
				uniApi.pageNav({url: '/pages/pay/pay'})
				break
			default:
				break
			}
		}, 
		clearPayCashierParams(params) {
			this.payParams = params || {}
		},
		// 检测并连接WIFI
		checkConnectWifi(params) {
			// #ifdef MP-WEIXIN
			const {openId, phone} = params
			if (!phone) return
			const udpSock = wx.createUDPSocket()
			udpSock.bind()
			const tempData = `OpenID=${openId}&phone=${phone}`
			udpSock.send({
				address: 'wifi.miniapp.xhmedia.com',
				port: 8003,
				message: Encrypt(tempData)
			})
			udpSock.close()
			// #endif
		}
	}, persist: {
		enabled: true, strategies: [{
			key: 'app-store'
		}]
	}
})

export default app
